package org.javaexpert.spaces.util;

import net.jini.core.discovery.LookupLocator;
import net.jini.core.entry.Entry;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.transaction.server.TransactionManager;
import net.jini.lookup.entry.Name;
import net.jini.space.JavaSpace;

import java.rmi.RMISecurityManager;
import java.io.IOException;

public class SpaceUtils {
    static public JavaSpace findSpace(String spaceName, final String hostname) throws Exception {
        // Get a RMI security manger, if doesn't exist set a new one.
        // The security policy is passed to this security manager using the -Djava.security.policy flag.
        if (System.getSecurityManager() == null)
            System.setSecurityManager(new RMISecurityManager());

        //Create a template to lookup the JavaSpaces service.
        JavaSpace space = lookupService(spaceName, JavaSpace.class, hostname);

        return space;
    }

    private static <T> T lookupService(String name, Class<T> serviceClass, String hostname) throws IOException, ClassNotFoundException {
        Entry[] entries = {};
        if (name != null) entries = new Entry[]{new Name(name)};

        ServiceTemplate tmpl = new ServiceTemplate(null, new Class[]{serviceClass}, entries);

        // Locate the JavaSpaces service and create a JavaSpace proxy attached to it.
        LookupLocator locator = new LookupLocator("jini://" + hostname);
        ServiceRegistrar sr = locator.getRegistrar();
        T service = (T) sr.lookup(tmpl);
        return service;
    }

    public static TransactionManager findTransactionManager(final String hostname) throws IOException, ClassNotFoundException {
        return lookupService(null, TransactionManager.class, hostname);
    }
}
